package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从session中获取登陆用户信息
        //Employee employee = (Employee)request.getSession().getAttribute("USER_IN_SESSION");
        Employee employee = UserContext.getContextUser();
        //判断该用户是不是超管
        if(employee.isAdmin()){
            //是超管就放行
            return true;
        }
        //不是超管还要进行下面的操作
        //handler是否是handlerMethod类型    若是 进行强转  若不是代表被拦截到的是静态资源   需要放行
        if(handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod)handler;
            RequiredPermission methodAnnotation = method.getMethodAnnotation(RequiredPermission.class);
            //判断该方法是否有贴权限注解
            if(methodAnnotation==null){
                return true;
            }
            //获取当前登陆用户拥有的权限表达式的集合
            //List<String> expressions = (List<String>)request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");
            List<String> expressions = UserContext.getExpression();
            //获取当前方法的权限表达式
            String expression = methodAnnotation.expression();
            if(!expressions.contains(expression)){
                response.sendRedirect("/nopermission");
            }
        }
        return true;//放行被拦截的静态资源
    }
}
